﻿using Core;
using System;
using System.Collections.Generic;

namespace Core
{

    public class ConfigComponent : Entity, IAwake
    {
        private Dictionary<Type, BaseLoader> loaderDict = new Dictionary<Type, BaseLoader>();
        private Dictionary<Type, BaseLoader> configDict = new Dictionary<Type, BaseLoader>();

        void IAwake.Awake()
        {
            var configAttribute = typeof(ConfigAttribute);
            var types = World.GetComponent<CodeTypes>().GetTypes(configAttribute);

            foreach ((string _, Type type) in types)
            {
                object[] attrs = type.GetCustomAttributes(configAttribute, false);
                if (attrs.Length == 0)
                    continue;

                var attribute = attrs[0] as ConfigAttribute;
                var instance = Activator.CreateInstance(type) as BaseLoader;
                if (instance == null)
                    continue;

                instance.Load(attribute.type);
                configDict[attribute.type] = instance;
                loaderDict[type] = instance;
            }
            
        }

        public T GetConfig<T>(int id) where T : class, IConfig
        {
            if (configDict.TryGetValue(typeof(T), out var mapConfig))
            {
                return mapConfig.Get(id) as T;
            }
            return default;
        }

        public T[] GetAllConifg<T>() where T : class, IConfig
        {
            if (configDict.TryGetValue(typeof(T), out var mapConfig))
            {
                var all = mapConfig.GetAll();
                T[] result = new T[all.Length];
                for (int i = 0; i < all.Length; i++)
                {
                    result[i] = all[i] as T;
                }
                return result;
            }
            return default;
        }
        public T GetLoader<T>() where T : BaseLoader
        {
            loaderDict.TryGetValue(typeof(T), out var loader);
            return loader as T;
        }
    }

}